package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {
    public static final long BEGIN_TIMESTAMP = 1735689600;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    /**
     * 序列号的位数
     */
    private static final int COUNT_BITS = 32;

    public Long nextId(String keyPrefix) {
        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowEpochSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timetamp = nowEpochSecond-BEGIN_TIMESTAMP;
        //生成自增序列号
        String data = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
        Long increment = stringRedisTemplate.opsForValue().increment("icr" + keyPrefix + data);

        //拼接

        return timetamp<<COUNT_BITS|increment;
    }
//    public static  void  main(String[] args){
//        LocalDateTime dateTime = LocalDateTime.of(2025, 1, 1, 0, 0, 0);
//        long epochSecond = dateTime.toEpochSecond(ZoneOffset.UTC);
//        System.out.println(epochSecond);
//    }

}
